package com.vercon.moensmart.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
import com.vercon.common.utils.DensityUtils
import com.vercon.common.utils.LogUtils
import com.vercon.moensmart.R
import com.vercon.moensmart.databinding.FragmentWifiConfirmBinding
import com.vercon.moensmart.dialog.base.BaseDialogFragment

class WIFIConfirmDialog() : BaseDialogFragment<FragmentWifiConfirmBinding?>() {
    private var listener: OnConfirmListener? = null
    private var mListener: ViewTreeObserver.OnGlobalLayoutListener? = null
    private var mTreeObserver: ViewTreeObserver? = null
    private var mButtonHeight = 0
    private var handler: Handler? = null
    private var name : String? = null
    override fun onCreateViewBinding(
        inflater: LayoutInflater,
        parent: ViewGroup?
    ): FragmentWifiConfirmBinding {
        return FragmentWifiConfirmBinding.inflate(inflater, parent, false)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        return dialog
    }

    override val isFullScreen: Boolean
        protected get() = false

    override fun initView(view: View?) {
        buttonBeyondKeyboardLayout(binding!!.parent, binding!!.childView)
        binding!!.title.text = resources.getString(R.string.wifi_input_password)
        binding!!.wifiName.text = name
        binding!!.noTV.isSelected = true
        binding!!.yesTV.setOnClickListener({ v: View? ->
            if (listener != null) {
                hideKeyboard(v)
                listener!!.onYse(
                    binding!!.wifiName.getText().toString(),
                    binding!!.passwordET.getText().toString()
                )
            }
        })
        binding!!.noTV.setOnClickListener({ v: View? ->
            if (listener != null) {
                hideKeyboard(v)
                listener!!.onNo()
            }
        })
        binding!!.passwordET.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                val password = binding!!.passwordET.text.toString().trim { it <= ' ' }
                if (password.length >= 8) {
                    binding!!.yesTV.isClickable = true
                    binding!!.yesTV.isSelected = true
                    binding!!.yesTV.setTextColor(resources.getColor(com.vercon.common.R.color.color_45A1C9)
                    )
                } else {
                    binding!!.yesTV.isClickable = false
                    binding!!.yesTV.isSelected = false
                    binding!!.yesTV.setTextColor(resources.getColor(com.vercon.common.R.color.color_7C7D88)
                    )
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })
        handler = Handler()
        handler!!.postDelayed(Runnable { showKeyboard() }, 500)
    }

    fun showKeyboard() {
        LogUtils.e("showKeyboard")
        if (binding!!.passwordET != null) {
            //设置可获得焦点
            binding!!.passwordET.isFocusable = true
            binding!!.passwordET.isFocusableInTouchMode = true
            //请求获得焦点
            binding!!.passwordET.requestFocus()
            //调用系统输入法
            val inputManager = binding!!.passwordET
                .context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.showSoftInput(binding!!.passwordET, 0)
        }
    }

    override fun initListener(view: View?) {}
    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (handler != null) {
            handler!!.removeCallbacksAndMessages(null)
        }
    }

    fun setOnConfirmListener(listener: OnConfirmListener?) {
        this.listener = listener
    }

    interface OnConfirmListener {
        fun onYse(ssid: String?, password: String?)
        fun onNo()
    }

    fun setWIFIName(name: String) {
        if (!TextUtils.isEmpty(name)) {
            this.name = name
        }
    }

    /**
     * 移动的布局
     *
     * @param root   需要移动的布局
     * @param button 最底部的布局
     */
    private fun buttonBeyondKeyboardLayout(root: View, button: View) {
        mListener = object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                Log.e("测试", "-------统计测量------")
                val rect = Rect()
                // 获得当前窗口的可视区域的大小
                activity!!.window.decorView.getWindowVisibleDisplayFrame(rect)
                // 当前窗口的高度 - 可见区域的底部 = 不可见窗体的大小[即软件盘的高度]
                val rootInvisibleHeight = activity!!.window.decorView.height - rect.bottom

                // 事件为弹出软键盘时，软件盘至少有100px吧 这里100可以替换为软件盘的高度
                if (rootInvisibleHeight > 100) {
                    val location = IntArray(2)
                    // 获得按钮即所要检测的视图的高
                    button.getLocationInWindow(location)
                    // 按钮的底部------
                    val buttonHeight = button.height + location[1]
                    // **************  判断是否需要进行移动 **************
                    if (rect.bottom > buttonHeight) {
                        // 如果不需要移动那么直接移除
                        if (mListener != null && mTreeObserver!!.isAlive) {
                            mTreeObserver!!.removeOnGlobalLayoutListener(this)
                        }
                        mListener = null
                    } else {
                        // 计算向上移动的高度
                        mButtonHeight =
                            (buttonHeight - rect.bottom + DensityUtils.dip2px(context, 20f))
                        Log.e("软键盘", "onGlobalLayout:   = $mButtonHeight")
                        // 注意scroll,移动的是内容
                        root.scrollTo(0, mButtonHeight)
                    }
                } else {
                    // 软键盘隐藏进行还原
                    root.scrollTo(0, 0)
                }
            }
        }
        mTreeObserver = root.viewTreeObserver
        mTreeObserver?.addOnGlobalLayoutListener(mListener)
    }

    companion object {
        private val name = ""
    }
}